// test_aliyun_bailian.js - 测试阿里云百炼平台API连接
const dotenv = require('dotenv');
const path = require('path');
const axios = require('axios');

// 加载环境变量
dotenv.config({ path: path.resolve(__dirname, '.env') });

async function testAliyunBailian() {
    try {
        const apiKey = process.env.ALIYUN_BAILIAN_API_KEY;
        const baseUrl = process.env.ALIYUN_BAILIAN_BASE_URL || "https://dashscope.aliyuncs.com/api/v1";
        const modelName = process.env.ALIYUN_EMBEDDING_MODEL || "text-embedding-v1";
        
        if (!apiKey) {
            console.error("错误: 未设置 ALIYUN_BAILIAN_API_KEY");
            return;
        }
        
        console.log("测试阿里云百炼平台API连接...");
        console.log("API密钥设置:", apiKey ? "已设置" : "未设置");
        console.log("基础URL:", baseUrl);
        console.log("模型名称:", modelName);
        
        // 测试API连接
        console.log("正在调用阿里云百炼平台嵌入API...");
        const response = await axios.post(
            `${baseUrl}/services/embeddings/text-embedding/text-embedding`,
            {
                model: modelName,
                input: {
                    texts: ["测试文本"]
                }
            },
            {
                headers: {
                    "Authorization": `Bearer ${apiKey}`,
                    "Content-Type": "application/json",
                    "X-DashScope-Async": "disable"
                },
                timeout: 10000 // 10秒超时
            }
        );
        
        console.log("API调用成功!");
        console.log("响应状态:", response.status);
        console.log("响应数据结构:", Object.keys(response.data));
        
        // 检查响应数据结构
        if (response.data.output && response.data.output.embeddings) {
            console.log("嵌入向量数量:", response.data.output.embeddings.length);
            if (response.data.output.embeddings.length > 0) {
                console.log("第一个嵌入向量维度:", response.data.output.embeddings[0].embedding.length);
            }
        } else {
            console.log("响应数据:", JSON.stringify(response.data, null, 2));
        }
        
    } catch (error) {
        console.error("API调用失败:");
        console.error("错误消息:", error.message);
        console.error("错误代码:", error.code);
        if (error.response) {
            console.error("响应状态:", error.response.status);
            console.error("响应头:", error.response.headers);
            console.error("响应数据:", JSON.stringify(error.response.data, null, 2));
        }
    }
}

testAliyunBailian();